<template>
  <div class="location-container">
    <!-- 顶部按钮 -->
    <div class="query-bar">
<!--      <el-button type="primary" @click="startAll">开始实时定位</el-button>-->
<!--      <el-button @click="stopAll">停止定位</el-button>-->
      <el-select
          v-model="query.relationType"
          placeholder="关系类型"
          clearable
          style="width: 120px"
      >
        <el-option label="配偶" value="配偶" />
        <el-option label="子女" value="子女" />
        <el-option label="其他" value="其他" />
      </el-select>

      <el-input
          v-model="query.realName"
          placeholder="老人姓名"
          clearable
          style="width: 160px; margin-left: 8px"
      />

      <el-button type="primary" @click="loadElderlyList" style="margin-left: 8px">
        查询
      </el-button>

      <el-button @click="resetQuery" style="margin-left: 8px">
        重置
      </el-button>

    </div>

    <!-- 老人卡片 -->
    <div class="card-grid">
      <div
          v-for="elderly in boundElderlyList"
          :key="elderly.elderlyUserId"
          class="card elderly-card"
          :class="{ active: elderly.elderlyUserId === currentElderlyId }"
          @click="openDrawer(elderly.elderlyUserId)"
      >
        <img :src="elderly.avatarUrl" class="avatar" />
        <div class="info">
          <div class="name">{{ elderly.realName }}</div>
          <div class="relation">{{ elderly.relationType }}</div>
        </div>
      </div>
    </div>

    <el-dialog
        v-model="dialogVisible"
        title="当前老人 实时定位"
        width="80%"
        top="5vh"
    >
      <div style="margin-bottom:10px">
        <el-button type="primary" @click="locateNow">刷新位置</el-button>
        <el-button @click="toggleTrack">{{
            showTrack ? '隐藏轨迹' : '显示轨迹'
          }}</el-button>
        <el-button type="warning" @click="fenceDrawer = true">
          电子围栏
        </el-button>
      </div>

      <!-- 地图容器 -->
      <div id="baidu-map" style="width:100%;height:60vh" />

      <!-- 围栏抽屉 -->
      <el-drawer v-model="fenceDrawer" title="电子围栏" direction="rtl" size="400px">
        <FenceDrawer   :elderly-user-id="currentElderlyId"
        />
<!--        v-model:visible="fenceDrawerVisible"-->
      </el-drawer>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { loadBMap } from '@/utils/bmap-loader'
import FenceDrawer from './FenceDrawer.vue'
import {ElMessage} from "element-plus";
import { initBMap } from '@/utils/init-bmap';
import { gpsToBaidu } from '@/utils/coord-transform';
import { inject } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
/* -------------------- 卡片数据 -------------------- */
const avatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')
const outOfFence = ref(false)

/* -------------------- 地图 -------------------- */
let marker, circle
const dialogVisible = ref(false)
const fenceDrawer = ref(false)
const showTrack = ref(false)
const fenceDrawerVisible = ref(false) // 抽屉开关
const currentElderlyId = inject('currentElderlyId')
const currentUser = inject('currentUser')
const boundElderlyList = ref([])
const query = ref({ relationType: '', realName: '' })
const loading = ref(false)
const elderlyList = ref([])
const BASE_URL = 'http://localhost:8080'
const token = localStorage.getItem('token')

let map = null
let watchId = null
let currentPoint = null
let trackPoints = []
let polyline = null


/* ----------  loadElderlyList ---------- */
//

const loadElderlyList = async () => {
  if (!currentUser.value?.userId) {
    ElMessage.error('用户未登录或登录已过期')
    return
  }
  loading.value = true
  try {
    const { data: res } = await axios.get(
        `${BASE_URL}/api/v1/family_user/elderly/boundElderly/search`,
        {
          params: {
            familyUserId: currentUser.value.userId,
            realName: query.value.realName || undefined,
            relationType: query.value.relationType || undefined
          },
          headers: { Authorization: `Bearer ${token}` }
        }
    )

    const list = res?.data || []
    if (!Array.isArray(list)) {
      console.warn('老人列表接口返回格式异常', res)
      return
    }

    boundElderlyList.value = list.map((e) => ({
      elderlyUserId: e.elderlyUserId,
      realName: e.realName,
      relationType: e.relationType,
      avatarUrl: e.avatarUrl || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
    }))
  } catch (error) {
    console.error('获取老人列表失败', error)
    ElMessage.error('获取老人列表失败')
  } finally {
    loading.value = false
  }
}

const resetQuery = () => {
  query.value = { relationType: '', realName: '' }
  loadElderlyList()
}

const openDrawer = async (elderlyUserId) => {
  currentElderlyId.value = elderlyUserId
  localStorage.setItem('currentElderlyId', String(elderlyUserId))
  dialogVisible.value = true

  await nextTick()
  setTimeout(async () => {
    if (!map) {
      map = await initBMap('baidu-map')
    }
    map.clearOverlays()
    locateNow()
  }, 300)
}

// 修改 initMap 签名
const initMap = (container) => {
  if (map) return
  map = new BMapGL.Map(container)
  map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 16)
  map.enableScrollWheelZoom(true)
}

/* 实时定位 */
const locateNow = async () => {
  if (!navigator.geolocation) return ElMessage.error('浏览器不支持定位');
  navigator.geolocation.getCurrentPosition(async (pos) => {
    try {
      const { longitude, latitude } = pos.coords;
      const baiduPoint = await gpsToBaidu(longitude, latitude);

      if (!marker) {
        marker = new BMapGL.Marker(baiduPoint);
        map.addOverlay(marker);
      } else {
        marker.setPosition(baiduPoint);
      }

      map.panTo(baiduPoint);
      currentPoint = baiduPoint; // 更新当前点

      // 添加到轨迹点
      trackPoints.push(baiduPoint);
      if (showTrack.value) drawTrack();
      checkFence();
    } catch (error) {
      ElMessage.error('坐标转换失败: ' + error.message);
    }
  }, () => ElMessage.error('定位失败'), { enableHighAccuracy: true });
}

/* 轨迹 */
const drawTrack = () => {
  if (polyline) map.removeOverlay(polyline)

  // 确保所有点都是有效的 BMapGL.Point 对象
  const validPoints = trackPoints.filter(point =>
      point instanceof BMapGL.Point && !isNaN(point.lng) && !isNaN(point.lat)
  )

  if (validPoints.length < 2) return

  polyline = new BMapGL.Polyline(validPoints, {
    strokeColor: '#409eff',
    strokeWeight: 4,
    strokeOpacity: 0.8
  })
  map.addOverlay(polyline)
}
const switchElderly = (id) => {
  localStorage.setItem('currentElderlyId', String(id))
  location.reload() // 或重新设置 currentElderlyId
}
/* 围栏 */
const updateFence = ({ center, radius }) => {
  if (circle) map.removeOverlay(circle)
  circle = new BMapGL.Circle(center, radius, {
    strokeColor: '#f56c6c',
    fillColor: '#f56c6c22',
    strokeWeight: 2
  })
  map.addOverlay(circle)
  checkFence()
}
const checkFence = () => {
  if (!circle || !currentPoint) return
  const distance = map.getDistance(circle.getCenter(), currentPoint)
  outOfFence.value = distance > circle.getRadius()
}

// /* 按钮 */
// const startAll = async () => {
//   if (navigator.geolocation) {
//     watchId = navigator.geolocation.watchPosition(
//         async (pos) => {
//           try {
//             const { longitude, latitude } = pos.coords;
//             const baiduPoint = await gpsToBaidu(longitude, latitude);
//
//             currentPoint = baiduPoint;
//             if (!marker) {
//               marker = new BMapGL.Marker(currentPoint);
//               map.addOverlay(marker);
//             } else {
//               marker.setPosition(currentPoint);
//             }
//
//             map.panTo(currentPoint);
//             trackPoints.push(currentPoint);
//             if (showTrack.value) drawTrack();
//             checkFence();
//           } catch (error) {
//             console.error('坐标转换失败:', error);
//           }
//         },
//         (error) => {
//           console.error('定位失败:', error);
//           ElMessage.error('定位失败: ' + error.message);
//         },
//         { enableHighAccuracy: true, timeout: 10000, maximumAge: 30000 }
//     )
//   }
// }

onMounted(async () => {
  await loadElderlyList()
  if (!currentElderlyId.value && boundElderlyList.value.length > 0) {
    const first = boundElderlyList.value[0]
    currentElderlyId.value = first.elderlyUserId
    localStorage.setItem('currentElderlyId', String(first.elderlyUserId))
  }
})

onMounted(async () => {
  await loadBMap();
  initMap();
});

</script>

<style scoped>
.location-container {
  padding: 20px;
}
.query-bar {
  margin-bottom: 20px;
}
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}
.card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: 0.3s;
}
.card.danger {
  border: 2px solid #f56c6c;
  background: #fef0f0;
}
.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-bottom: 10px;
}
.name {
  font-weight: bold;
  font-size: 16px;
}
.relation {
  font-size: 14px;
  color: #666;
}
</style>